<?php

namespace App\Http\Controllers\Backstage\Company\Task;

use App\Ant\WithUpload;
use App\Events\TaskEvent;
use App\Http\Controllers\BaseController;
use App\Http\Requests\Backstage\Company\Archive\UploadRequest;
use App\Http\Requests\Backstage\Company\Task\Furniture\CreateRequest;
use App\Http\Requests\Backstage\Company\Task\Furniture\UpdateRequest;
use App\Models\Company\Task\Furniture;
use App\Transformers\Company\FurnitureTransformer;
use App\Transformers\MediaTransformer;

class FurnitureController extends BaseController
{
    use WithUpload;

    public function index()
    {
        $page_size = get_request_page();
        $furniture = Furniture::orderBy('created_at', 'desc')->paginate($page_size);
        return $this->response->paginator($furniture, new FurnitureTransformer());
    }

    public function store(CreateRequest $request)
    {
        $model = \DB::transaction(function () use ($request) {
            $data = $request->validated();
            $model = Furniture::create($data);
            return $model;
        });
        event(new TaskEvent($model));
        return $this->response->noContent();
    }

    public function show($id)
    {
        $model = Furniture::find($id);
        return $this->response->item($model, new FurnitureTransformer());
    }

    public function update(UpdateRequest $request, $id)
    {
        \DB::transaction(function () use ($request, $id) {
            $attributes = $request->validated();
            $furniture = Furniture::find($id);
            $model = $furniture->update($attributes);
            return $model;
        });
        return $this->response->noContent();
    }

    public function upload(UploadRequest $request)
    {
        $model = $this->addUpload($request);
        return $this->response->item($model, new MediaTransformer());
    }
}
